<?php

namespace App\utils;

use Illuminate\Support\Facades\DB;
use Intervention\Image\Facades\Image;

class ImageUploader
{
    protected $ext_allowed = ['jpg','png','jpeg','gif'];

    public function save($file,$folder='avatars',$user_id,$max_width=false,$del_old=false):array
    {
        //新建文件夹
        $folder_name = 'uploads/images/'.$folder.'/'.date('Ym/d',time());

        //上传地址
        $upload_path = public_path().'/'.$folder_name;

        $ext = strtolower($file->getClientOriginalExtension())??'unknown';

        if(!in_array($ext,$this->ext_allowed)){
            return [];
        }

        $filename = md5($user_id.time()).'.'.$ext;
        $file->move($upload_path,$filename);

        //gif不缩放
        if($max_width && $ext !=='gif'){
            $this->resize($upload_path.'/'.$filename,$max_width);
        }
        //删除原有头像
        if($del_old){
            $this->delOldImage($user_id);
        }


        return [
            'path' => '/'.$folder_name.'/'.$filename
        ];

    }

    /*
     * 等比缩放
     * */
    public function resize($file_path,$max_width)
    {
        $image = Image::make($file_path);
        $image->resize($max_width,null,function($obj){
            //等比例缩放
            $obj->aspectRatio();
            //不扩张
            $obj->upsize();
        });
        $image->save();
    }

    /*
     * 删除旧图片
     * */
    public function delOldImage($user_id){

        $user = DB::table('users')->find($user_id);
        if($user){
            @unlink(public_path().$user->avatar);
        }
        return true;
    }

}
